import axios from 'axios'
import { ElMessage } from 'element-plus'
import type {
  AxiosInstance,
  InternalAxiosRequestConfig,
  AxiosResponse,
} from 'axios'
import type { Response, RequestInterface } from '@/types/request'

const axiosInstance: AxiosInstance = axios.create({
  baseURL: '/api',
  // timeout: 10000,
})

axiosInstance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    if (!config.headers['Content-Type']) {
      config.headers['Content-Type'] = 'application/json'
    }
    return config
  },
  (error) => {
    console.log('error', error)
    return Promise.reject(error)
  },
)

axiosInstance.interceptors.response.use(
  (response: AxiosResponse<RequestInterface<any>, any>) => {
    if (!(response.status >= 200 && response.status < 300)) {
      ElMessage({
        type: 'error',
        message: '网络错误，请检查网络后再试！',
      })
      return Promise.reject('网络错误，请检查网络后再试！')
    }
    if (response.data.code >= 200 && response.data.code < 300) {
      return response.data.data
    }
    if (response.data.code === 501) {
      ElMessage({
        type: 'warning',
        message: response.data.message,
      })
      return Promise.reject(response.data.message)
    }
    if (response.data.code === 500) {
      ElMessage({
        type: 'error',
        message: response.data.message,
      })
      return Promise.reject(response.data.message)
    }
    return Promise.reject(response.data.message)
  },
  (error) => {
    ElMessage({
      type: 'error',
      message: '网络错误，请检查网络后再试！',
    })
    return Promise.reject(error)
  },
)

export const get = <T = any>(
  url: string,
  params = {},
  headers = {},
): Response<T> => {
  return axiosInstance({
    url,
    method: 'get',
    params,
    headers,
  })
}

export const post = <T = any>(
  url: string,
  params = {},
  headers = {},
): Response<T> => {
  return axiosInstance({
    url,
    method: 'post',
    data: params,
    headers,
  })
}
